package main

import (
	"cybertwin/pb/model"
	"cybertwin/utils/generator" // 随机生成一些数值
	"cybertwin/utils/nettools"  // 用于获取mac地址
	"cybertwin/utils/protocol"
	"fmt"
	"net"
	"os"

	log "github.com/sirupsen/logrus"

	"time"

	"flag"

	"github.com/rs/zerolog" //日志框架
	"google.golang.org/protobuf/proto"
)

var n = flag.Int("n", 100, "-n 100: 输入的创建数量")

func init() {
	zerolog.TimeFieldFormat = time.DateTime
}

func registerUE(ctid string, uid string, hid string, macAddr string) (ueid string) {
	// 注册协议封装
	ueType := generator.GenRandomUeType()
	file, err := os.ReadFile("./ca/ue/ue_pk_1.pem")
	if err != nil {
		log.Errorln("[RegisterUE]-读取./ca/ue/ue_pk_1.pem文件失败:", err.Error())
		return
	}
	registerParam := &model.RegisterParam{
		MsgId:       "123",
		Mac:         macAddr,
		UeName:      generator.GenRandomUeName(ueType),
		UeType:      ueType,
		CybertwinId: ctid,
		Uid:         uid,
		Hid:         hid,
		UePublicKey: string(file),
	}

	codec := protocol.AccessProtocolCodec{}
	marshal, err := proto.Marshal(registerParam) // 序列化请求参数
	if err != nil {
		log.Errorln("[RegisterUE]-序列化registerParam失败:", err.Error())
		return
	}
	encode, err := codec.EncryptEncode(marshal, protocol.TYPE_REGISTER) // 生成协议
	if err != nil {
		log.Errorln("[RegisterUE]-EncryptEncode registerParam失败:", err.Error())
		return
	}
	dial, err := net.Dial("tcp", "127.0.0.1:8080")
	defer dial.Close()
	size, err := dial.Write(encode)
	if err != nil {
		log.Errorln("[RegisterUE]-向注册中心write数据失败:", err.Error())
		return
	}
	log.Infof("[RegisterUE]-发送注册请求，%dbytes数据", size)

	var buf = make([]byte, 1024)
	size, err = dial.Read(buf)
	buf = buf[:size]
	if err != nil {
		log.Errorln("[RegisterUE]-读取注册消息失败", err.Error())
		return
	}
	data, typeName, _, err := codec.DecodeFromBytes(buf)
	if typeName != protocol.TYPE_RESPONSE.GetName() {
		log.Errorln("[RegisterUE]-类型错误，expected:TYPE_RESPONSE, actual:%s", typeName)
		return
	}
	resp := &model.RegisterResp{}
	err = proto.Unmarshal(data, resp)
	if err != nil {
		log.Errorln("[RegisterUE]-反序列化RegisterResp失败")
		return
	}
	return resp.UeId
}

func main() {
	flag.Parse()
	log.Infof("[RegisterUE-main]-解析到命令行参数为%d", n)
	fileName := "ue_info.txt"
	file, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Errorf("[RegisterUE-main]-打开文件/创建文件失败: %s", err.Error())
		return
	}
	for i := 0; i < *n; i++ {
		macAddr, err := nettools.GetMacAddr("192.168.101.100")
		if err != nil {
			macAddr = generator.GenRandomMacAddr()
		}
		ctid := "ue_0222b78c-b3ff-4a0f-8dc2-11ee40a36ac5"
		uid := "user_01"
		hid := generator.GenerateHid(macAddr, uid, generator.RandomInt(4, 16))
		ueid := registerUE(ctid, uid, hid, macAddr)
		file.Write([]byte(fmt.Sprintf("%s %s\n", ueid, hid)))
	}
}
